<template>
  <div class="view-print" id="custom-content">
    <avue-form :option="option" v-model="form" style="width: 95%;"></avue-form>
    <div
      class="VRorm-render-list"
      v-for="(item, index) in data"
      :key="item.id"
      style="margin-top: 10px"
    >
      <div class="VRorm-render-list-hint">
        <span style="margin-right: 10px">采集时间：{{ item.createTime }}</span>
        <span>备 注：{{ item.remark }}</span>
      </div>
      <div class="VRorm-render-list-title">
        {{ item.name }}
      </div>
      <VFormRender
        style="padding: 15px"
        :form-json="JSON.parse(item.question)"
        :form-data="JSON.parse(item.content)"
        :option-data="optionData"
        :ref="el => setFormRef(el, index)"
      >
      </VFormRender>
    </div>
  </div>
</template>
<script setup>
import printJS from 'print-js';
import VFormRender from '@/components/form-render/index.vue';
import {
  getDetail,
  eleMedicalRecordDetail,
  eleMedicalRecordList,
} from '@/api/casemanagement/caseManagement';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const router = useRouter();
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const option = ref({
  detail: true,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: '120',
  column: [
    {
      label: '姓名',
      prop: 'name',
      type: 'input',
    },
    {
      label: '性别',
      prop: 'sex',
      type: 'select',
      dicUrl: '/api/blade-system/dict/dictionary?code=sex',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
    },
    {
      label: '手机号',
      prop: 'phone',
      type: 'input',
    },
    {
      label: '电话号',
      prop: 'dhh',
      type: 'input',
    },
    {
      label: '简称',
      prop: 'nameSx',
      type: 'input',
    },
    {
      label: '民族',
      prop: 'mz',
      type: 'input',
    },
    {
      label: '出生日期',
      prop: 'birthday',
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
    {
      label: '病历号',
      prop: 'zyh',
      type: 'input',
    },
    {
      label: '邮箱',
      prop: 'mailbox',
      type: 'input',
      span: 24,
    },
    {
      label: '疾病种类',
      prop: 'jbzl',
      type: 'tree',
      dicUrl: '/api/blade-illness/illness/tree',
      props: {
        label: 'title',
        value: 'id',
      },
      span: 24,
    },
    {
      label: '现住地',
      prop: 'jzd',
      type: 'input',
      span: 24,
    },
    {
      label: '详细地址',
      prop: 'address',
      type: 'input',
      span: 24,
    },
    {
      label: '现病史',
      prop: 'bs',
      type: 'input',
      span: 24,
    },
    {
      label: '诊断',
      prop: 'diagnosis',
      type: 'input',
      span: 24,
    },
  ],
});
let form = ref({});
let data = ref([]);

const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});

const vFormRefs = ref([]); // 保存所有子组件实例的数组
const formJson = ref({});
// const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});
// 动态绑定 ref 到数组
const setFormRef = (el, index) => {
  if (el) {
    vFormRefs.value[index] = el;
  }
};
const open = val => {
  page.value.pageSize = val;
  initEleMedicalRecordList(page.value);
};

const initEleMedicalRecordList = page => {
  let values = {
    descs: 'create_time',
    caseId: routerQuery.value.caseManagementId,
  };
  eleMedicalRecordList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    data.value = DATA.records;
    setTimeout(() => {
      handlePrintCrf(data.value);
    }, 1000);
  });
};

const handlePrintCrf = data => {
  nextTick(() => {
    // 遍历所有子组件实例并调用方法
    data.forEach((item, index) => {
      const formJson = JSON.parse(item.question);
      console.log(formJson, vFormRefs.value[index]);

      if (vFormRefs.value[index]) {
        vFormRefs.value[index].setFormJson(formJson);
      }
    });
    setTimeout(() => {
      printJS({
        printable: 'custom-content', // 容器 ID
        type: 'html', // 指定打印类型为 HTML
        //   style: `                      // 自定义打印样式（可选）
        //   @page { size: A4; margin: 10mm; }
        //   h2 { color: #333; }
        //   .content-box { border: 1px solid #ddd; padding: 10px; }
        // `,
        style: `
            @media print {
              .el-input__prefix,
              .el-input__suffix {
                display: none !important;
              }
                /* 增强隐藏效果 */
        .el-select__caret, 
        .el-input__suffix, 
        .el-icon-arrow-up {
          display: none !important;
          width: 0 !important;
          height: 0 !important;
        }
        
        /* 保持输入框样式 */
        .el-input__inner {
          border: 1px solid #000 !important;
          background: #fff !important;
          -webkit-appearance: none;
          appearance: none;
        }

        /* 隐藏其他不需要的元素 */
        .el-dialog__wrapper,
        .el-popper,
        .el-select-dropdown {
          display: none !important;
          opacity: 0 !important;
        }
            }
          `,
        scanStyles: false, // 是否扫描页面样式（true 时会继承页面原有样式）
        targetStyles: ['*'], // 指定继承哪些页面样式（['*'] 表示全部）
        // ignoreElements: ['button'], // 隐藏容器内不需要打印的元素（可选）
        onPrintDialogClose: () => {
          // 打印完成后恢复样式（可选）
          document.querySelectorAll('.el-input__inner').forEach(input => {
            input.style.cssText = '';
          });
        },
      });
    }, 500);
  });
};

onMounted(() => {
  if (routerQuery.value.caseManagementId) {
    initGetDetail(routerQuery.value.caseManagementId);
  }
});

const initGetDetail = async caseManagementId => {
  let res = await getDetail(caseManagementId);
  form.value = res.data.data;
};

defineExpose({
  open,
});
</script>
<style scoped lang="scss">
.VRorm-render-list {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
}
.VRorm-render-list-hint {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  font-size: 18px;
  color: black;
  font-weight: 550;
}
.VRorm-render-list-title {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #337ab7;
  border-bottom: 1px double black;
}
@media print {
  .el-input__prefix,
  .el-input__suffix {
    display: none !important;
  }
}
@media print {
  /* 强制avue-form保持原有布局 */
  .avue-form__row {
    display: flex !important;
    flex-wrap: wrap !important;
  }
  
  /* 修复span布局 */
  .avue-form-item {
    flex: 0 0 calc(100% / 24 * var(--span)) !important; /* 动态span */
    max-width: calc(100% / 24 * var(--span)) !important;
    float: none !important;
    display: inline-block !important;
    page-break-inside: avoid;
  }

  /* 修复ElementUI组件 */
  .el-form-item {
    display: inline-block !important;
    width: auto !important;
    margin-right: 10px !important;
  }
  
  /* 全局打印优化 */
  body, html {
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
  }
  
  /* 防止换行 */
  .el-input, .el-select, .el-date-editor {
    display: inline-block !important;
    width: auto !important;
  }
}
</style>